package com.heima.search.service.impl;

import cn.hutool.core.convert.Convert;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.dto.UserThreadLocalUtil;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.search.dto.ApArticleSearchDto;
import com.heima.search.entity.ApArticleSearch;
import com.heima.search.repository.ArticleRepository;
import com.heima.search.service.ArticleSearchService;
import com.heima.search.service.IApUserSearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author : wuqiang
 * @date : 2022年10月23日
 */
@Service
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private IApUserSearchService apUserSearchService;


    /**
     * 搜索
     *
     * @param dto dto
     * @return {@link ResponseResult}
     */
    @Override
    public ResponseResult search(ApArticleSearchDto dto) {
        if (dto == null || StringUtils.isBlank(dto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        if (dto.getSize() < 0) {
            dto.setSize(1);
        }
        if (dto.getSize() < 0) {
            dto.setSize(20);
        }

        Integer page = Convert.toInt(dto.getPage() - 1);
        QueryBuilder query = QueryBuilders.matchQuery("title", dto.getSearchWords());

        Pageable pageRequest = PageRequest.of(page, dto.getSize(), Sort.by(Sort.Direction.DESC, "publishTime"));
        Page<ApArticleSearch> search = articleRepository.search(query, pageRequest);
        List<ApArticleSearch> content = search.getContent();

        //搜索的关键字存储
        //不能影响正常数据返回  包括错误信息 时间
        User user = UserThreadLocalUtil.get();
        if (user != null) {
            apUserSearchService.saveSearchRecord(dto.getSearchWords(), user, dto.getEquipmentId());
        }
        return ResponseResult.okResult(content);
    }

}
